'''



'''

from ... import QtCore, QtGui
from .. import ValueEditorMixin


class ChoiceEditor(QtGui.QComboBox, ValueEditorMixin):
    def __init__(self, parent, controller, options):
        QtGui.QComboBox.__init__(self, parent)
        
        try:
            self.labeled_choices = options['labeled_choices']
        except KeyError:
            self.labeled_choices = [ (i,i) for i in options.get('choices') ]
        self.addItems([ str(l) for l, v_ in self.labeled_choices ])
        self.label_to_value = dict(self.labeled_choices)
        
        ValueEditorMixin.__init__(self, controller, options)
        
    def get_value(self):
        return self.labeled_choices[self.currentIndex()][1]
    
    def set_value(self, value):
        ValueEditorMixin.set_value(self, value)
        for index, (l, v) in enumerate(self.labeled_choices):
            if v == value:
                self.setCurrentIndex(index)
                return
        
        # not found...
        self.addItem(str(value))
        self.labeled_choices.append((str(value), value))
        index = len(self.labeled_choices)
        self.setCurrentIndex(index)

    def _set_edit_connections(self):
        #self.currentIndexChanged.connect(self.edit_finished)
        self.currentIndexChanged.connect(self._on_change)

    def _set_read_only(self, b):
        self.setEnabled(not b)

    def _on_change(self):
        self.edit_finished()
        